#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author : gao
# Time : 2020/7/8 14:09

"""
    文件说明：根据训练数据，计算各种需要的概率
"""

import CreateData as cd
import numpy as np

def trainModel(trainX,trainY):
    '''
    计算概率
    :param trainX: 训练集矩阵
    :param trainY: 训练标签list
    :return: 侮辱的概率，侮辱的条件概率的对数，非侮辱的条件概率的对数
    '''
    #一共cols组数据
    rows = len(trainX)
    #一共rows词（列）
    cols = len(trainX[0])
    #计算侮辱性的频率（拉普拉是修正的）
    pAbuse = (sum(trainY)+1)/(rows+2)
    #带拉普拉斯修正的侮辱条件下和非侮辱条件下，各单词的的次数向量
    abuseVec = np.ones(cols)
    nonAbuseVec = np.ones(cols)
    #带拉普拉斯修正德侮辱和非侮辱的数据量
    abuseNum =2.0+sum(trainY)
    nonAbuseNum =2.0+rows-sum(trainY)
    for i in range(rows):
        if trainY[i]==1:#是侮辱
            abuseVec+=trainX[i]
        else:
            nonAbuseVec+=trainX[i]
    #取对数，防止n个较小的数相乘溢出
    pAbuseI = np.log(abuseVec / abuseNum)
    pNonI = np.log(nonAbuseVec / nonAbuseNum)
    return pAbuse,pAbuseI,pNonI


def classifyNB(trainX,trainY,x):
    """

    :param trainX:
    :param trainY:
    :param x: 待分类样本
    :return: True是侮辱 False 不是侮辱
    """
    pAbuse, pAbuseI, pNonI = trainModel(trainX, trainY)
    p1 = sum(x*pAbuseI)+np.log(pAbuse)
    p0 = sum(x*pNonI)+np.log(1-pAbuse)
    print('是：',str(p1))
    print('否：',str(p0))
    result = p1>=p0
    if result:
        return 1
    return 0


if __name__ == '__main__' :
    trainX,trainY=cd.loadData()
    result = classifyNB(trainX,trainY,[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
    print('是否侮辱',str(result))

